<template>
  <div class="order-container">
    <div class="top-actions">
      <div>
        <el-button type="primary" @click="router.push('/createOrder')">新建订单</el-button>
        <el-button type="success" plain>导出订单</el-button>
      </div>
      <div class="search-box">
        <el-input v-model="searchKeyword" placeholder="订单号/收件人/发件人" clearable>
          <template #append>
            <el-button :icon="Search" />
          </template>
        </el-input>
      </div>
    </div>

    <!-- 订单列表 -->
    <el-table :data="filteredOrders" style="width: 100%" v-loading="loading">
      <el-table-column prop="orderNumber" label="订单号" min-width="140" />
      <el-table-column prop="createTime" label="创建时间" min-width="160" />
      <el-table-column prop="senderName" label="发件人" min-width="100" />
      <el-table-column prop="senderPhone" label="发件人电话" min-width="120" />
      <el-table-column prop="recipientName" label="收件人" min-width="100" />
      <el-table-column prop="recipientPhone" label="收件人电话" min-width="120" />
      <el-table-column prop="weight" label="重量(kg)" min-width="90" />
      <el-table-column prop="freight" label="运费(元)" min-width="90" />
      <el-table-column prop="status" label="状态" min-width="100">
        <template #default="scope">
          <el-tag :type="getStatusTag(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="180" fixed="right">
        <template #default="scope">
          <el-button link type="primary" @click="viewOrder(scope.row)">查看</el-button>
          <el-button link type="primary" @click="updateStatus(scope.row)" :disabled="scope.row.status === 3">
            更新状态
          </el-button>
          <el-button link type="danger" @click="deleteOrder(scope.row)" :disabled="scope.row.status !== 0">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalItems"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新建订单对话框 -->
    <el-dialog v-model="dialogVisible" title="新建订单" width="680px">
      <el-form :model="orderForm" label-width="100px" :rules="rules" ref="orderFormRef">
        <el-divider content-position="left">寄件人信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="寄件人姓名" prop="senderName">
              <el-input v-model="orderForm.senderName" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="寄件人电话" prop="senderPhone">
              <el-input v-model="orderForm.senderPhone" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="寄件地址" prop="senderAddress">
          <el-input v-model="orderForm.senderAddress" />
        </el-form-item>

        <el-divider content-position="left">收件人信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="收件人姓名" prop="recipientName">
              <el-input v-model="orderForm.recipientName" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收件人电话" prop="recipientPhone">
              <el-input v-model="orderForm.recipientPhone" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="收件地址" prop="recipientAddress">
          <el-input v-model="orderForm.recipientAddress" />
        </el-form-item>

        <el-divider content-position="left">物品信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="物品类型" prop="itemType">
              <el-select v-model="orderForm.itemType" placeholder="请选择">
                <el-option label="文件" value="document" />
                <el-option label="服装" value="clothing" />
                <el-option label="电子产品" value="electronics" />
                <el-option label="生活用品" value="daily" />
                <el-option label="其他" value="other" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="重量(kg)" prop="weight">
              <el-input-number v-model="orderForm.weight" :min="0.1" :step="0.1" @change="calculateFreight" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="估值(元)" prop="declaredValue">
              <el-input-number v-model="orderForm.declaredValue" :min="0" :step="100" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注">
          <el-input v-model="orderForm.remark" type="textarea" :rows="2" />
        </el-form-item>

        <el-divider content-position="left">运费信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="运费(元)" prop="freight">
              <el-input-number v-model="orderForm.freight" :min="0" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="支付方式" prop="paymentMethod">
              <el-radio-group v-model="orderForm.paymentMethod">
                <el-radio label="online">在线支付</el-radio>
                <el-radio label="cod">货到付款</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitOrder">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 状态更新对话框 -->
    <el-dialog v-model="statusDialogVisible" title="更新订单状态" width="400px">
      <el-form :model="statusForm" label-width="100px">
        <el-form-item label="当前状态">
          <el-tag :type="getStatusTag(currentOrder.status)">
            {{ getStatusText(currentOrder.status) }}
          </el-tag>
        </el-form-item>
        <el-form-item label="新状态">
          <el-select v-model="statusForm.status">
            <el-option
              v-for="option in statusOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
              :disabled="option.value <= currentOrder.status"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="statusForm.remark" type="textarea" :rows="2" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="statusDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmUpdateStatus">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'

const router = useRouter()

// 示例数据
const orderList = ref([
  {
    id: 1,
    orderNumber: 'LG202405070001',
    createTime: '2024-05-07 08:30:25',
    senderName: '张三',
    senderPhone: '13800138001',
    senderAddress: '上海市闵行区莘庄工业区',
    recipientName: '李四',
    recipientPhone: '13900139001',
    recipientAddress: '北京市海淀区中关村',
    weight: 2.5,
    freight: 45,
    status: 2,
    itemType: 'electronics',
    declaredValue: 1000,
    paymentMethod: 'online',
    remark: '轻拿轻放，谢谢'
  },
  {
    id: 2,
    orderNumber: 'LG202405070002',
    createTime: '2024-05-07 09:15:37',
    senderName: '王五',
    senderPhone: '13700137001',
    senderAddress: '广州市天河区天河路',
    recipientName: '赵六',
    recipientPhone: '13600136001',
    recipientAddress: '深圳市南山区科技园',
    weight: 1.2,
    freight: 25,
    status: 1,
    itemType: 'document',
    declaredValue: 200,
    paymentMethod: 'online',
    remark: ''
  },
  {
    id: 3,
    orderNumber: 'LG202405070003',
    createTime: '2024-05-07 10:45:12',
    senderName: '陈七',
    senderPhone: '13500135001',
    senderAddress: '成都市武侯区天府大道',
    recipientName: '钱八',
    recipientPhone: '13400134001',
    recipientAddress: '重庆市渝中区解放碑',
    weight: 5.8,
    freight: 85,
    status: 0,
    itemType: 'clothing',
    declaredValue: 500,
    paymentMethod: 'cod',
    remark: '尽快送达，谢谢'
  }
])

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const totalItems = ref(3)

// 搜索相关
const searchKeyword = ref('')
const loading = ref(false)

// 表单相关
const dialogVisible = ref(false)
const orderFormRef = ref(null)
const orderForm = reactive({
  senderName: '',
  senderPhone: '',
  senderAddress: '',
  recipientName: '',
  recipientPhone: '',
  recipientAddress: '',
  itemType: '',
  weight: 1,
  declaredValue: 0,
  remark: '',
  freight: 0,
  paymentMethod: 'online'
})

// 表单验证规则
const rules = {
  senderName: [{ required: true, message: '请输入寄件人姓名', trigger: 'blur' }],
  senderPhone: [
    { required: true, message: '请输入寄件人电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  senderAddress: [{ required: true, message: '请输入寄件地址', trigger: 'blur' }],
  recipientName: [{ required: true, message: '请输入收件人姓名', trigger: 'blur' }],
  recipientPhone: [
    { required: true, message: '请输入收件人电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  recipientAddress: [{ required: true, message: '请输入收件地址', trigger: 'blur' }],
  itemType: [{ required: true, message: '请选择物品类型', trigger: 'change' }],
  weight: [{ required: true, message: '请输入重量', trigger: 'blur' }],
  paymentMethod: [{ required: true, message: '请选择支付方式', trigger: 'change' }]
}

// 状态更新相关
const statusDialogVisible = ref(false)
const currentOrder = ref({} as any)
const statusForm = reactive({
  status: 0,
  remark: ''
})

const statusOptions = [
  { label: '待揽收', value: 0 },
  { label: '已揽件', value: 1 },
  { label: '运输中', value: 2 },
  { label: '已签收', value: 3 }
]

// 计算运费
const calculateFreight = () => {
  // 简单的运费计算逻辑，实际项目中可以根据距离、重量等因素计算
  if (orderForm.weight <= 1) {
    orderForm.freight = 20
  } else {
    orderForm.freight = 20 + (orderForm.weight - 1) * 10
  }
}

// 根据状态获取标签类型
const getStatusTag = (status: number) => {
  const statusMap: Record<number, string> = {
    0: 'info',
    1: 'primary',
    2: 'warning',
    3: 'success'
  }
  return statusMap[status] || 'info'
}

// 根据状态获取文本
const getStatusText = (status: number) => {
  const statusMap: Record<number, string> = {
    0: '待揽收',
    1: '已揽件',
    2: '运输中',
    3: '已签收'
  }
  return statusMap[status] || '未知状态'
}

// 过滤订单列表
const filteredOrders = computed(() => {
  if (!searchKeyword.value) return orderList.value
  
  const keyword = searchKeyword.value.toLowerCase()
  return orderList.value.filter(order => 
    order.orderNumber.toLowerCase().includes(keyword) ||
    order.senderName.toLowerCase().includes(keyword) ||
    order.recipientName.toLowerCase().includes(keyword) ||
    order.senderPhone.includes(keyword) ||
    order.recipientPhone.includes(keyword)
  )
})

// 分页事件处理
const handleSizeChange = (val: number) => {
  pageSize.value = val
  // 这里应该重新加载数据
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  // 这里应该重新加载数据
}

// 查看订单
const viewOrder = (row: any) => {
  // 实际项目中可能跳转到订单详情页或打开详情弹窗
  ElMessage.info(`查看订单：${row.orderNumber}`)
}

// 更新状态
const updateStatus = (row: any) => {
  currentOrder.value = row
  statusForm.status = row.status + 1
  statusForm.remark = ''
  statusDialogVisible.value = true
}

// 确认更新状态
const confirmUpdateStatus = () => {
  // 实际项目中这里应该调用API
  const index = orderList.value.findIndex(o => o.id === currentOrder.value.id)
  if (index !== -1) {
    orderList.value[index].status = statusForm.status
    ElMessage.success('订单状态更新成功')
    statusDialogVisible.value = false
  }
}

// 删除订单
const deleteOrder = (row: any) => {
  ElMessageBox.confirm(
    `确认删除订单 ${row.orderNumber} 吗？此操作不可恢复`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 实际项目中这里应该调用API
    const index = orderList.value.findIndex(o => o.id === row.id)
    if (index !== -1) {
      orderList.value.splice(index, 1)
      totalItems.value--
      ElMessage.success('订单删除成功')
    }
  }).catch(() => {
    // 取消操作
  })
}

// 提交表单
const submitOrder = () => {
  if (!orderFormRef.value) return
  
  orderFormRef.value.validate((valid: boolean) => {
    if (valid) {
      // 实际项目中这里应该调用API
      const newOrder = {
        id: orderList.value.length + 1,
        orderNumber: `LG${new Date().getTime().toString().slice(0, 10)}`,
        createTime: new Date().toLocaleString(),
        status: 0,
        ...orderForm
      }
      
      orderList.value.unshift(newOrder)
      totalItems.value++
      ElMessage.success('订单创建成功')
      dialogVisible.value = false
      
      // 重置表单
      orderForm.senderName = ''
      orderForm.senderPhone = ''
      orderForm.senderAddress = ''
      orderForm.recipientName = ''
      orderForm.recipientPhone = ''
      orderForm.recipientAddress = ''
      orderForm.itemType = ''
      orderForm.weight = 1
      orderForm.declaredValue = 0
      orderForm.remark = ''
      orderForm.freight = 0
      orderForm.paymentMethod = 'online'
    }
  })
}

// 页面加载时的操作
onMounted(() => {
  // 实际项目中这里应该加载订单数据
  loading.value = true
  setTimeout(() => {
    loading.value = false
  }, 500)
})
</script>

<style scoped>
.order-container {
  padding: 20px;
}

.top-actions {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.search-box {
  width: 300px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 